package com.sunday.fangdaifu.common;

import android.app.ProgressDialog;
import android.content.Context;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.sunday.common.base.BaseApplication;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.NetworkUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.volley.AuthFailureError;
import com.sunday.common.volley.DefaultRetryPolicy;
import com.sunday.common.volley.Request;
import com.sunday.common.volley.Response;
import com.sunday.common.volley.VolleyError;
import com.sunday.common.volley.toolbox.MultipartParams;
import com.sunday.common.volley.toolbox.MultipartRequest;
import com.sunday.common.volley.toolbox.StringRequest;
import com.sunday.fangdaifu.base.MyApplication;

import java.io.File;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;




/**
 *
 */
public class ApiServiceImpl implements ApiService {


    private static Gson gson = null;
    private Context mContext;

    public ApiServiceImpl(Context context) {
        gson = new Gson();
        mContext = context;
    }

    private HashMap<String, String> getDeviceInfo() {
        HashMap<String, String> maps = new HashMap<>();
        return maps;
    }


    public interface HttpResponseInterface {
        void onResponce(String key, Object result);

        void onFailure();
    }

    private Request executeApi(final String key, final HashMap<String, String> params, ProgressDialog dialog,
                               final HttpResponseInterface response, final Type type) {
        StringRequest request = new StringRequest(Request.Method.POST, key, new Response.Listener<String>() {
            @Override
            public void onResponse(String key, String responseTxt) {
                if (type != null) {
                    Object result = gson.fromJson(responseTxt, type);
                    if (result instanceof ResultDO) {
                        response.onResponce(key, result);
                    } else {
                        response.onFailure();
                    }
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(String key, VolleyError error) {
                if (response != null) {
                    response.onFailure();
                }
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return params;
            }
        };
        if (!NetworkUtils.isConnectInternet(mContext)) {
            ToastUtils.showToast(mContext, "网络不给力");
            return request;
        }
        request.setRetryPolicy(new DefaultRetryPolicy(
                30000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        MyApplication.getInstance().getRequestQueue().add(request);
        return request;
    }

    @Override
    public void login(int type, String username, String password, final ApiServiceImpl.HttpResponseInterface response, final Type types) {
        HashMap<String, String> params = getDeviceInfo();
        params.put("username", username);
        if (!TextUtils.isEmpty(password)) {
            params.put("password", password);
        }
        params.put("type", "1");
        executeApi(Api.LOGIN, params, null, response, types);
    }

    @Override
    public void sendCode(String mobile, HttpResponseInterface response, Type types) {
        HashMap<String, String> params = getDeviceInfo();
        if (!TextUtils.isEmpty(mobile)) {
            params.put("mobile", mobile);
        }
        executeApi(Api.SEND_CODE, params, null, response, types);
    }

    @Override
    public void checkCode(String mobile, String activeCode, HttpResponseInterface response, Type types) {
        HashMap<String, String> params = getDeviceInfo();
        if (!TextUtils.isEmpty(mobile)) {
            params.put("mobile", mobile);
        }
        if (!TextUtils.isEmpty(activeCode)) {
            params.put("activeCode", activeCode);
        }
        executeApi(Api.CHECK_CODE, params, null, response, types);
    }

    @Override
    public void settingPwd(int userId, String password, HttpResponseInterface response, Type types) {
        HashMap<String, String> params = getDeviceInfo();
        params.put("userId", String.valueOf(userId));
        if (!TextUtils.isEmpty(password)) {
            params.put("password", password);
        }
        executeApi(Api.SETTING_PWD, params, null, response, types);
    }

    @Override
    public void dateTitle(HttpResponseInterface response, Type types) {
        executeApi(Api.DATE_TITLE, null, null, response, types);
    }

    @Override
    public void dateList(int itemId, int pageNo, int pageSize, HttpResponseInterface response, Type types) {
        HashMap<String, String> params = getDeviceInfo();
        params.put("itemId", String.valueOf(itemId));
        params.put("pageNo", String.valueOf(pageNo));
        params.put("pageSize", String.valueOf(pageSize));
        executeApi(Api.DATE_LIST, params, null, response, types);
    }

    @Override
    public void dateBanner(int itemId, HttpResponseInterface response, Type types) {
        HashMap<String, String> params = getDeviceInfo();
        params.put("itemId", String.valueOf(itemId));
        executeApi(Api.DATE_BANNER, params, null, response, types);
    }

    @Override
    public void indexTask(int userId, HttpResponseInterface response, Type types) {
        HashMap<String, String> params = getDeviceInfo();
        params.put("userId", String.valueOf(userId));
        executeApi(Api.INDEX_TASK, params, null, response, types);
    }

    @Override
    public void indexTaskCount(int userId, HttpResponseInterface response, Type types) {
        HashMap<String, String> params = getDeviceInfo();
        params.put("userId", String.valueOf(userId));
        executeApi(Api.INDEX_TASK_COUNT, params, null, response, types);
    }

    @Override
    public void taskDetail(int id, HttpResponseInterface response, Type types) {
        HashMap<String, String> params = getDeviceInfo();
        params.put("id", String.valueOf(id));
        executeApi(Api.TASK_DETAIL, params, null, response, types);
    }

    @Override
    public void taskList(int userId, int type, int status, int pageNo, int pageSize, HttpResponseInterface response, Type types) {
        HashMap<String, String> params = getDeviceInfo();
        params.put("userId", String.valueOf(userId));
        params.put("type", String.valueOf(type));
        params.put("status", String.valueOf(status));
        params.put("pageNo", String.valueOf(pageNo));
        params.put("pageSize", String.valueOf(pageSize));
        executeApi(Api.TASK_LIST, params, null, response, types);
    }

    @Override
    public void unFinishTaskList(int userId, int status, int pageNo, int pageSize, HttpResponseInterface response, Type types) {
        HashMap<String, String> params = getDeviceInfo();
        params.put("userId", String.valueOf(userId));
        params.put("status", String.valueOf(status));
        params.put("pageNo", String.valueOf(pageNo));
        params.put("pageSize", String.valueOf(pageSize));
        executeApi(Api.UNFINISH_TASK_LIST, params, null, response, types);
    }

    @Override
    public void taskCount(int userId, HttpResponseInterface response, Type types) {
        HashMap<String, String> params = getDeviceInfo();
        params.put("userId", String.valueOf(userId));
        executeApi(Api.TASK_COUNT, params, null, response, types);
    }

    @Override
    public void historyReportList(int houseId, int pageNo, int pageSize, HttpResponseInterface response, Type types) {
        HashMap<String, String> params = getDeviceInfo();
        params.put("houseId", String.valueOf(houseId));
        params.put("pageNo", String.valueOf(pageNo));
        params.put("pageSize", String.valueOf(pageSize));
        executeApi(Api.HISTORY_REPORT_LIST, params, null, response, types);
    }

    @Override
    public void historyReportDetail(int id, HttpResponseInterface response, Type types) {
        HashMap<String, String> params = getDeviceInfo();
        params.put("id", String.valueOf(id));
        executeApi(Api.HISTORY_REPORT_DETAIL, params, null, response, types);
    }

    @Override
    public void taskId(int userId, int houseId, HttpResponseInterface response, Type types) {
        HashMap<String, String> params = getDeviceInfo();
        params.put("userId", String.valueOf(userId));
        params.put("houseId", String.valueOf(houseId));
        executeApi(Api.TASK_ID, params, null, response, types);
    }

    @Override
    public void getPartsList(HttpResponseInterface response, Type types) {
        HashMap<String, String> params = getDeviceInfo();
        executeApi(Api.PARTS_LIST, params, null, response, types);
    }

    @Override
    public void getPartsTypeList(int id, HttpResponseInterface response, Type types) {
        HashMap<String, String> params = getDeviceInfo();
        params.put("id", String.valueOf(id));
        executeApi(Api.PARTS_TYPE_LIST, params, null, response, types);
    }

    @Override
    public void getProblemList(int id, HttpResponseInterface response, Type types) {
        HashMap<String, String> params = getDeviceInfo();
        params.put("id", String.valueOf(id));
        executeApi(Api.PROBLEM_LIST, params, null, response, types);
    }

    @Override
    public void changeTaskStatus(int id, int type, String latitude, String longitude, HttpResponseInterface response, Type types) {
        HashMap<String, String> params = getDeviceInfo();
        params.put("id", String.valueOf(id));
        params.put("type", String.valueOf(type));
        if (!TextUtils.isEmpty(latitude)) {
            params.put("latitude", latitude);

        }
        if (!TextUtils.isEmpty(longitude)) {
            params.put("longitude", longitude);
        }
        executeApi(Api.CHANGE_TASK_STATUS, params, null, response, types);
    }

    @Override
    public void uploadSingle(String filePath, final HttpResponseInterface responses, final Type types) {
        MultipartParams maps = new MultipartParams();
        File file = new File(filePath);
        maps.put(file.getName(), file);
        MultipartRequest request = new MultipartRequest(Api.UP_LOAD_SINGLE_IMG, maps, new Response.Listener<String>() {
            @Override
            public void onResponse(String key, String response) {
                if (types != null) {
                    Object result = gson.fromJson(response, types);
                    if (result instanceof ResultDO) {
                        responses.onResponce(key, result);
                    } else {
                        responses.onFailure();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(String key, VolleyError error) {
                if (responses != null) {
                    responses.onFailure();
                }
            }
        });
        MyApplication.getInstance().getRequestQueue().add(request);
    }



    @Override
    public void uploadMulti(List<String> filePaths, final HttpResponseInterface responses, final Type types) {
        MultipartParams maps = new MultipartParams();
        File file = null;
        for (String item : filePaths) {
            file = new File(item);
            maps.put(file.getName(), file);
        }
        MultipartRequest request = new MultipartRequest(Api.UP_LOAD_MULTI_IMG, maps, new Response.Listener<String>() {
            @Override
            public void onResponse(String key, String response) {
                if (types != null) {
                    Object result = gson.fromJson(response, types);
                    if (result instanceof ResultDO) {
                        responses.onResponce(key, result);
                    } else {
                        responses.onFailure();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(String key, VolleyError error) {
                if (responses != null) {
                    responses.onFailure();
                }
            }
        });
        MyApplication.getInstance().getRequestQueue().add(request);
    }

    @Override
    public void submitReport(int houseId, int detailId, String json, HttpResponseInterface response, Type types) {
        HashMap<String, String> params = getDeviceInfo();
        params.put("houseId", String.valueOf(houseId));
        params.put("detailId", String.valueOf(detailId));
        params.put("json", json);
        executeApi(Api.SUBMIT_REPORT, params, null, response, types);
    }

    @Override
    public void replyDirect(int id, String text, HttpResponseInterface response, Type types) {
        HashMap<String, String> params = getDeviceInfo();
        params.put("id", String.valueOf(id));
        params.put("text", text);
        executeApi(Api.REPLY_DIRECT, params, null, response, types);
    }

    @Override
    public void updateLogo(int userId, String logo, HttpResponseInterface response, Type types) {
        HashMap<String, String> params = getDeviceInfo();
        params.put("userId", String.valueOf(userId));
        params.put("logo", logo);
        executeApi(Api.UPDATE_LOGO, params, null, response, types);
    }

    //1，安卓巡检版本，2，安卓布控版，3，苹果巡检版，4，苹果布控版
    @Override
    public void checkUpdate(int type, int versionCode, HttpResponseInterface response, Type types) {
        HashMap<String, String> params = getDeviceInfo();
        params.put("type", String.valueOf(type));
        params.put("versionCode", String.valueOf(versionCode));
        executeApi(Api.UPDATE_APK, params, null, response, types);
    }


}
